import { Injectable } from '@nestjs/common';
// import { CreateUserDto } from './dto/create-user.dto';
// import { UpdateUserDto } from './dto/update-user.dto';
import { throwHttpException } from '@/utils/nesjUtils';

import { v4 as uuidv4 } from 'uuid';
import * as crypto from 'crypto';
import * as dayjs from 'dayjs';
import { ErrCode } from '@/types/globalType';
import type { IBaseUser, ILoginApiParams } from './types/index';
import prismaClient from '../../../config/prismaClient';
@Injectable()
export class UserService {
  // async create(createUserDto: CreateUserDto) {
  async create(createUserDto: IBaseUser) {
    // return 'This action adds a new user';
    const createCodeRes: object[] =
      await prismaClient.$queryRaw`CALL base_createEmployeeCode()`;
    if (createCodeRes.length == 0) {
      return {
        state: '0',
        msg: '生成用户编号失败！',
      };
    }

    try {
      const createUserRes = await prismaClient.base_user.create({
        data: {
          ID: uuidv4(),
          Code: (createCodeRes[0] as { f0: string }).f0,
          Name: createUserDto.Name,
          Phone: createUserDto.Phone,
          Email: createUserDto.Email,
          Password: crypto
            .createHash('sha256')
            .update(
              createUserDto.Password +
                Buffer.from('ddg', 'utf-8').toString('hex'),
            )
            .digest('hex'),
          Birthday: createUserDto.Birthday
            ? dayjs(createUserDto.Birthday).toISOString()
            : null,
          Gender: createUserDto.Gender ? createUserDto.Gender : '3',
          AvatarUrl: createUserDto.AvatarUrl,
          ProvienceCode: createUserDto.ProvienceCode,
          CityCode: createUserDto.CityCode,
          CountyCode: createUserDto.CountyCode,
          Note: createUserDto.Note,
          IsDel: '0',
          Creator: 'sys',
          CreateTime: dayjs().toISOString(),
          LastModifier: 'sys',
          LastModifyTime: dayjs().toISOString(),
          // LastModifyTime: '233232',
        },
      });
      console.log('createUserRes', createUserRes);
      return {
        state: '1',
        msg: '创建成功！',
        data: createUserRes,
      };
    } catch (error) {
      console.log('error', error);
      // error
      throwHttpException({
        errCode: ErrCode.CodeError,
        // errmsg: error.stack,
        // errmsg: error.message,
        // errmsg: error.name,
        // errmsg: error.clientVersion,
        errMsg: '注册失败！',
        errStack: error.message,
      });
    }

    // const crypto = require('crypto');

    // // 输入字符串
    // const message = 'Hello, World!';

    // // 生成随机盐值
    // const salt = crypto.randomBytes(16).toString('hex');

    // // 将消息和盐值连接在一起，然后生成 SHA-256 哈希值
    // const hashWithSalt = crypto
    //   .createHash('sha256')
    //   .update(message + salt)
    //   .digest('hex');

    // // 输出结果
    // console.log('Salt:', salt); // 随机生成的盐值
    // console.log('Hash with salt:', hashWithSalt); // 加盐后的哈希值
  }

  // 登录
  async login(params: ILoginApiParams) {
    const baseUserList = await prismaClient.base_user.findMany({
      where: {
        Phone: params.Phone,
        IsDel: '0',
      },
    });
    return baseUserList[0];
  }

  async batchDel(ids: string[], tokenPayload) {
    const updateUsers = await prismaClient.base_user.updateMany({
      where: {
        ID: { in: ids },
      },
      data: {
        IsDel: '1',
        Creator: tokenPayload.ID,
        CreateTime: dayjs().toISOString(),
        LastModifier: tokenPayload.ID,
        LastModifyTime: dayjs().toISOString(),
      },
    });
    return updateUsers.count;
  }

  async update(record, tokenPayload) {
    try {
      const updateUsers = await prismaClient.base_user.updateMany({
        where: {
          ID: record.ID,
        },
        data: {
          Name: record.Name,
          Phone: record.Phone,
          Email: record.Email,
          Birthday: record.Birthday
            ? dayjs(record.Birthday).toISOString()
            : null,
          Gender: record.Gender ? record.Gender : '3',
          AvatarUrl: record.AvatarUrl || null,
          ProvienceCode: record.ProvienceCode,
          CityCode: record.CityCode,
          CountyCode: record.CountyCode,
          Note: record.Note,
          LastModifier: tokenPayload.ID,
          LastModifyTime: dayjs().toISOString(),
        },
      });
      return updateUsers.count;
    } catch (error) {
      throwHttpException({
        errCode: ErrCode.CodeError,
        errMsg: '更新失败！',
        errStack: error.message,
      });
    }
  }

  async batchQueryByIDs(ids: string[]) {
    return await prismaClient.base_user.findMany({
      where: {
        ID: { in: ids },
        IsDel: '0',
      },
    });
  }

  async updateUserPassword(id, newPassword, tokenPayload) {
    try {
      const updateUsers = await prismaClient.base_user.updateMany({
        where: {
          ID: id,
        },
        data: {
          Password: crypto
            .createHash('sha256')
            .update(newPassword + Buffer.from('ddg', 'utf-8').toString('hex'))
            .digest('hex'),
          LastModifier: tokenPayload.ID,
          LastModifyTime: dayjs().toISOString(),
        },
      });
      return updateUsers.count;
    } catch (error) {
      throwHttpException({
        errCode: ErrCode.CodeError,
        errMsg: '修改密码失败！',
        errStack: error.message,
      });
    }
  }
}
